import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/merchant/GoodsGuige.dart';
import 'package:shop/shop/merchant/Index.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
// import 'package:awesome_dropdown/awesome_dropdown.dart';
/**
 * 服务型商品添加或编辑
 */
class ServiceEdit extends StatefulWidget {
  List guiges = [];     //商品规格集合
  String gName;String danwei;String miaoshu;String goodsTypeName;//商品信息
  int type;             //类型  1：新增  2：修改
  String id;            //商品ID
  String fuwuPicture;   //服务图片json
  String detailPicture; //详情图片json
  ServiceEdit({Key key, this.title, this.guiges,this.goodsTypeName,this.miaoshu,this.gName,this.danwei,this.type,this.id,this.fuwuPicture,this.detailPicture}) : super(key: key);

  final String title;

  @override
  _ServiceEdit createState() => _ServiceEdit(guiges,goodsTypeName,miaoshu,gName,danwei,type,id,fuwuPicture,detailPicture);
}

class _ServiceEdit extends State<ServiceEdit> {

  TextEditingController _gName;
  TextEditingController _danwei;
  TextEditingController _miaoshu;

  var isMoreGuige=false;//是否支持多规格
  List<DropdownMenuItem> goodsTypeList = []; //商品类型集合
  var goodsTypeName;    //商品类型名称
  var merchantType;     //店铺类型
  String merchantID;    //商户ID
  int type=1;           //类型  1：新增  2：修改
  String id;            //商品ID
  String fuwuPictures;  //服务图片json
  String detailPictures;//详情图片json
  SharedPreferences prefs;
  String mType="0";     //店铺类型

  List fuwuPicture = [];//服务图片集合
  List detailPicture = [];//详情图片集合
  List guiges = [];//商品规格集合
  String gName="";String danwei="";String miaoshu="";//商品信息
  _ServiceEdit(guiges,goodsTypeName,miaoshu,gName,danwei,type,id,fuwuPicture,detailPicture){
    this.guiges=guiges;
    this.fuwuPictures=fuwuPicture;
    this.detailPictures=detailPicture;
    this.gName=gName;this.miaoshu=miaoshu;this.danwei=danwei;
    this.type=type;this.id=id;
    if(goodsTypeName!=null && goodsTypeName!=""){
      this.goodsTypeName=goodsTypeName;
    }
    if(guiges.length>0){
      isMoreGuige = true;
    }
    _gName = new TextEditingController(text: gName);
    _danwei = new TextEditingController(text: danwei);
    _miaoshu = new TextEditingController(text: miaoshu);
    _getSundryInfo();
  }

  //得初始数据
  _getSundryInfo() async {
    // 获取内存存储的用户id
    prefs = await SharedPreferences.getInstance();
    if(prefs.getBool("isLogin")){
      mType = prefs.getString("mType");
      print("商户类型："+mType);
      merchantID = prefs.getString("merchantID");
      //得商家所有商品类型
      var x = await HttpUtil().get("/waimai/mGoodsType/getMerchantAllGoodsType?mId="+merchantID);
      if(x['code']==200){
        if(x['data'].length>0){
          if(goodsTypeName==null || goodsTypeName==""){
            goodsTypeName = x['data'][0]['name'];
          }
          for(int i=0;i<x['data'].length;i++){
            goodsTypeList.add(DropdownMenuItem(child: Text(x['data'][i]['name']),value: x['data'][i]['name'],),);
          }
        }
      }
      if(type==2){
        fuwuPicture = json.decode(fuwuPictures);
        detailPicture = json.decode(detailPictures);
      }
      setState(() {});
    }else{
      Fluttertoast.showToast(msg: "请先登录");
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      // appBar: AppBar(
      //   centerTitle: true,
      //   automaticallyImplyLeading: false,
      //   title: Text("服务"),
      // ),
      body: Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 5),
                decoration: BoxDecoration(
                  color: Colors.black12,
                ),
                child: Row(
                  children: [
                    Icon(Icons.warning_outlined,size: 20,color: Colors.red,),
                    Text("标"),Text("*",style: TextStyle(color: Colors.red),),
                    Text("为必填项，其余的为选填项")
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("服务名称"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(child: TextFormField(
                      controller: _gName,
                      decoration: InputDecoration(
                          hintText: "请输入服务名称",
                          hintStyle: TextStyle(fontSize: 14)
                        // border: InputBorder.none,
                      ),
                    ))
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                child: Row(
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("服务类型"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(
                      child: DropdownButton(
                        hint: Text("请选择服务类型"),
                        value: goodsTypeName,
                        items: goodsTypeList,
                        isExpanded: true,
                        onChanged: (value) {
                          setState(() {
                            goodsTypeName=value;
                          });
                        }
                      )
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                child: Row(
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red)),Text("服务单位"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(child:TextFormField(
                      controller: _danwei,
                      decoration: InputDecoration(
                          hintText: "次/人/位/....",
                          hintStyle: TextStyle(fontSize: 14)
                      ),
                    ))
                  ],
                ),
              ),
              // Container(
              //   padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              //   child: Row(
              //     children: [
              //       Row(children: [Text("*",style: TextStyle(color: Colors.red)),Text("预约方式"),SizedBox(width: 5,),],) ,
              //       Expanded(
              //         child:Row(children: [
              //           Checkbox(value: false, onChanged: (v){}),Text("电话预约"),
              //           Checkbox(value: false, onChanged: (v){}),Text("网上预约"),
              //         ],)
              //       )
              //     ],
              //   ),
              // ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                child: Row(
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red)),Text("服务简介"),SizedBox(width: 5,)],) ,
                    SizedBox(width: 30,),
                    Expanded(child:TextFormField(
                      controller: _miaoshu,
                      decoration: InputDecoration(
                        hintText: "请输入服务简介",
                        hintStyle: TextStyle(fontSize: 14)
                      ),
                    ))
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                decoration: BoxDecoration(
                  // color: Colors.red
                ),
                child: Row(
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red)),Text("详情图片"),SizedBox(width: 5,)],) ,
                    SizedBox(width: 30,),
                    Expanded(child: Wrap(
                      children: [
                        Wrap(
                            spacing: 5,
                            runSpacing: 5,
                            children:
                            _getDetailPicture()
                          // GestureDetector(child: CachedNetworkImage(imageUrl: "https://img2.baidu.com/it/u=3800037915,2368949556&fm=26&fmt=auto&gp=0.jpg",width: 50,),onLongPress: (){print("长按删除");},),
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                          child:GestureDetector(child: Row(
                            children: [
                              Container(
                                width: 60,
                                height: 60,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.black , width: 0) ,
                                ),
                                child: Center(child: Text("+"),),
                              ),
                            ],
                          ),onTap: () async {
                            var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                            File file = new File(s.path);// 获取文件路径
                            var res = await HttpUtil().upload("/upload", file);
                            detailPicture.add("tmp/"+res['data']);
                            setState(()  {

                            });
                          },),
                        ),
                      ],
                    ))
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                decoration: BoxDecoration(
                  // color: Colors.red
                ),
                child: Row(
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red)),Text("服务图片"),SizedBox(width: 5,)],) ,
                    SizedBox(width: 30,),
                    Expanded(child: Wrap(
                      children: [
                        Wrap(
                          spacing: 5,
                          runSpacing: 5,
                          children:
                            _getFuwuPicture()
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                          child:GestureDetector(child: Row(
                            children: [
                              Container(
                                width: 60,
                                height: 60,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.black , width: 0) ,
                                ),
                                child: Center(child: Text("+"),),
                              ),
                            ],
                          ),onTap: () async {
                            var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                            File file = new File(s.path);// 获取文件路径
                            var res = await HttpUtil().upload("/upload", file);
                            fuwuPicture.add("tmp/"+res['data']);
                            setState(()  {

                            });
                          },),
                        ),
                      ],
                    ))
                  ],
                ),
              ),
            ],
          )
          ),
          Container(
            child: Row(
              children: [
                Expanded(child: GestureDetector(
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Center(child: Text("保存"),),
                    color: Colors.red,
                  ),
                  onTap: () async {
                    gName = _gName.text.trim();danwei = _danwei.text.trim();miaoshu = _miaoshu.text.trim();
                    if(gName.length<1){Fluttertoast.showToast(msg: "服务名称不能为空");return ;}
                    // final reg = RegExp(r'^-?[0-9]+');// 验证是否为数字
                    // final zhengshu = RegExp(r'^[+]{0,1}(\d+)$');// 验证是否为正整数
                    // if(!reg.hasMatch(gPrice)){Fluttertoast.showToast(msg: "商品价格只能是数字");return ;}
                    if(danwei.length<1){Fluttertoast.showToast(msg: "服务单位不能为空");return ;}
                    if(miaoshu.length<1){Fluttertoast.showToast(msg: "服务简介不能为空");return ;}
                    if(fuwuPicture.length<1){Fluttertoast.showToast(msg: "请上传服务图片");return ;}
                    if(detailPicture.length<1){Fluttertoast.showToast(msg: "请上传详情图片");return ;}
                    var map = new HashMap<String,dynamic>();
                    String guige = json.encode(guiges);
                    map['gname']=gName;map['gtypeId']=goodsTypeName;map['gdanwei']=danwei;map['jianjie']=miaoshu;map['guige']=guige;
                    map['gimages']="11111";map['mid']=merchantID;
                    map['image6']="66666";
                    map['fuwuPicture'] = json.encode(fuwuPicture);map['detailPicture']=json.encode(detailPicture);
                    if(type==1){//新增商品
                      Response response = await HttpUtil().post("waimai/mGoods/addFuwuMGoods",map);
                      var x = json.decode(response.toString());
                      if(x['code']==200){
                        Fluttertoast.showToast(
                            msg: "新增成功"
                        );
                        MyRoute.push(Index(showIndex: "1",mType: mType,));
                      }else{
                        Fluttertoast.showToast(
                            msg: x['msg']
                        );
                      }
                    }else{//修改商品
                      map['id']=id;
                      Response response = await HttpUtil().post("waimai/mGoods/updateFuwuMGoods",map);
                      var x = json.decode(response.toString());
                      if(x['code']==200){
                        Fluttertoast.showToast(
                            msg: "修改成功"
                        );
                        MyRoute.push(Index(showIndex: "1",mType: mType,));
                      }else{
                        Fluttertoast.showToast(
                            msg: x['msg']
                        );
                      }
                    }
                  },
                ))
              ],
            ),
          ),
        ],
      ),
    );
  }

  /*图片控件*/
  Widget _ImageView(imgPath,tu) {
    if (tu == null) {
      return Center(
        child: Text("请选择图片或拍照"),
      );
    } else {
      // return type!=2 ? Image.network(Config.getInstance().getHost()+'tmp/'+tu,width: ScreenUtil().setWidth(90),height: ScreenUtil().setHeight(100),) : Image.network(Config.getInstance().getHost()+tu,width: ScreenUtil().setWidth(90),height: ScreenUtil().setHeight(100),);
      return Image.network(Config.getInstance().getHost()+tu,width: ScreenUtil().setWidth(90),height: ScreenUtil().setHeight(100),);
    }
  }

  //循环服务图片
  _getFuwuPicture(){
    List<Widget> x = [];
    for(int i=0;i<fuwuPicture.length;i++){
      x.add(GestureDetector(child: CachedNetworkImage(imageUrl: Config.getInstance().getHost()+fuwuPicture[i],width: 50,),onLongPress: (){
        // print("长按删除");print("下标："+i.toString());
        fuwuPicture.removeAt(i);
        setState(() {

        });
        },)
      );
    }
    return  x;
  }

  //循环详情图片
  _getDetailPicture(){
    List<Widget> x = [];
    for(int i=0;i<detailPicture.length;i++){
      x.add(GestureDetector(child: CachedNetworkImage(imageUrl: Config.getInstance().getHost()+detailPicture[i],width: 50,),onLongPress: (){
        detailPicture.removeAt(i);
        setState(() {

        });
      },)
      );
    }
    return  x;
  }

}
